//index.js
const app = getApp()
const moment = require("../../util/moment.js")
const {getData, request} = require("../../util/request.js")
Page({
    data: {
        imgUrl: null,
        avatarUrl: './user-unlogin.png',
        userInfo: {},
        userId: app.globalData.userId,
        logged: false,
        takeSession: false,
        requestResult: '',
        liveClass: [
        ],
        publicClass: [
        ],
        skillClass: [
        ]
    },
    onShareAppMessage: function (res) {
        return {
            title: '每天半小时，轻松拿本科',
            path: '/pages/index/index',//实验发现，此处的路径应该写全，写到具体的wxml页面。如path:'/page/user/user?id=123'
            success: function(res) {
                // 转发成功
            },
            fail: function(res) {
                // 转发失败
            }
        }
    },
    onLoad: function (res) {
        this.setData({
            userId: app.globalData.userId,
            userInfo: app.globalData.userInfo
        })
        let that = this
        getData('/mike', function (res) {
            if (res.error == 0) {
                that.setData({
                    liveClass: res.data.lives,
                    publicClass: res.data.public_courses,
                    skillClass: res.data.technical_courses
                })
            }

        }, function (err) {

        })
        if (!wx.cloud) {
            wx.redirectTo({
                url: '../chooseLib/chooseLib',
            })
            return
        }
        // 获取用户信息
        if (!app.globalData.openid) {
            wx.getSetting({
                success: res => {
                    if (res.authSetting['scope.userInfo']) {
                        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                        wx.getUserInfo({
                            success: res => {
                                app.globalData.userInfo = res.userInfo
                                this.setData({
                                    avatarUrl: res.userInfo.avatarUrl,
                                    userInfo: res.userInfo
                                })
                                this.onGetOpenid()
                            }
                        })
                    }
                }
            })
        } else {
            this.setData({
                avatarUrl: app.globalData.userInfo.avatarUrl,
                userInfo: app.globalData.userInfo
            })
        }

    },

    onGetUserInfo: function (e) {
        if (!this.logged && e.detail.userInfo) {
            this.setData({
                logged: true,
                avatarUrl: e.detail.userInfo.avatarUrl,
                userInfo: e.detail.userInfo
            })
        }
    },
    updateUserInfo() {
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            app.globalData.userInfo = res.userInfo
                            this.setData({
                                avatarUrl: res.userInfo.avatarUrl,
                                userInfo: res.userInfo
                            })
                            this.onGetOpenid()
                        }
                    })
                }
            }
        })
    },
    onGetOpenid: function () {
        let that = this
        // 调用云函数
        wx.cloud.callFunction({
            name: 'login',
            data: {},
            success: (res) => {
                app.globalData.openid = res.result.openid
                app.globalData.unionid = res.result.unionid
                // 设置本地缓存
                wx.setStorage({
                    key: 'openid',
                    data: res.result.openid,
                })
                wx.setStorage({
                    key: 'unionid',
                    data: res.result.unionid,
                })
                wx.setStorage({
                    key: 'userInfo',
                    data: that.data.userInfo,
                })
                // 登录
                request('/mike/auth/login', "POST",{unionid:res.result.unionid,openid:res.result.openid},function (res) {
                    if (res.error === 0) {
                        if (res.data.auth){
                            app.globalData.userId = res.data.user.user_id
                            app.globalData.user = res.data.user
                            that.setData({
                                userId: res.data.user.user_id,
                                is_mobile_binded: res.data.user.is_mobile_binded
                            })
                            wx.setStorage({
                                key: 'is_mobile_binded',
                                data: res.data.user.is_mobile_binded
                            })
                            wx.setStorage({
                                key: 'user',
                                data: res.data.user
                            })
                            wx.setStorage({
                                key: 'token',
                                data: res.data.auth.token_type + ' ' + res.data.auth.access_token,
                            })
                            wx.setStorage({
                                key: 'user_id',
                                data: res.data.user.user_id,
                            })
                        }else {
                            // 提示绑定
                            wx.navigateTo({
                                url: `../bind/bind`,
                            })
                        }
                    } else {
                        wx.showToast({
                            title: res.message,
                            icon: 'none'
                        })
                    }
                }, function (err) {

                })
            },
            fail: err => {
                wx.navigateTo({
                    url: '../deployFunctions/deployFunctions',
                })
            }
        })
    },

    // 上传图片
    doUpload: function () {
        // 选择图片
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: function (res) {

                wx.showLoading({
                    title: '上传中',
                })

                const filePath = res.tempFilePaths[0]

                // 上传图片
                const cloudPath = 'my-image' + filePath.match(/\.[^.]+?$/)[0]
                wx.cloud.uploadFile({
                    cloudPath,
                    filePath,
                    success: res => {
                        console.log('[上传文件] 成功：', res)

                        app.globalData.fileID = res.fileID
                        app.globalData.cloudPath = cloudPath
                        app.globalData.imagePath = filePath

                        wx.navigateTo({
                            url: '../storageConsole/storageConsole'
                        })
                    },
                    fail: e => {
                        console.error('[上传文件] 失败：', e)
                        wx.showToast({
                            icon: 'none',
                            title: '上传失败',
                        })
                    },
                    complete: () => {
                        wx.hideLoading()
                    }
                })

            },
            fail: e => {
                console.error(e)
            }
        })
    },
    onReachBottom() {
        // console.log('reach bottom')
    },
})
